﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SimpleUnitity
{
    [Serializable]
    public class DbData
    {
        static readonly StringComparer ignoreCaseComparer = StringComparer.Create(System.Globalization.CultureInfo.CurrentCulture, true);

        public DbData()
        {

        }

        public DbData(IDictionary<string, object> datas)
        {
            this.SetRange(datas);
        }

        private Dictionary<string, object> datas = new Dictionary<string, object>(ignoreCaseComparer);
        //private List<string> fields = new List<string>();

        public void SetRange(IDictionary<string, object> datas)
        {
            if (datas != null)
            {
                foreach (KeyValuePair<string, object> item in datas)
                {
                    this[item.Key] = item.Value;
                }
            }
        }

        public object this[string field]
        {
            get { return datas.ContainsKey(field) ? datas[field] : null; }
            set
            {
                if (value is DBNull)
                {
                    value = null;
                }
                if (datas.ContainsKey(field))
                {
                    datas[field] = value;
                }
                else
                {
                    datas.Add(field, value);
                }
            }
        }

        public bool Remove(string field)
        {
            if (datas.ContainsKey(field))
            {
                datas.Remove(field);
                return true;
            }
            else
            {
                return false;
            }
        }

        public string[] GetFields()
        {
            List<string> fields = new List<string>(datas.Keys);
            return fields.ToArray();
        }

        public object[] GetValues()
        {
            List<object> values = new List<object>();
            foreach (string field in datas.Keys)
            {
                values.Add(this[field]);
            }
            return values.ToArray();
        }

        public IDictionary<string, object> ToDictionary()
        {
            return new Dictionary<string, object>(datas, ignoreCaseComparer);
        }

    }
}
